package com.ruoyi.supermarket.service.impl;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.supermarket.domain.*;
import com.ruoyi.supermarket.domain.Vo.TempCxCcVO;
import com.ruoyi.supermarket.domain.Vo.TempCxDdVO;
import com.ruoyi.supermarket.mapper.*;
import com.ruoyi.system.mapper.SysUserMapper;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;
import com.ruoyi.supermarket.service.ITempCxService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 采销Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-05-19
 */
@Service
public class TempCxServiceImpl implements ITempCxService
{
    @Autowired
    private TempCxMapper tempCxMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private PurchaseMapper purchaseMapper;

    @Autowired
    private XqpurchaseMapper xqpurchaseMapper;

    @Autowired
    private SaleMapper saleMapper;

    @Autowired
    private XqsaleMapper xqsaleMapper;

    @Autowired
    private  StockMapper stockMapper;
    /**
     * 查询采销
     * 
     * @param tId 采销主键
     * @return 采销
     */
    @Override
    public TempCx selectTempCxByTId(Long tId)
    {
        return tempCxMapper.selectTempCxByTId(tId);
    }


    /**
     * 查询采销列表
     * 
     * @param tempCx 采销
     * @return 采销
     */
    @Override
    public List<TempCx> selectTempCxList(TempCx tempCx)
    {
        tempCx.setCreateId(SecurityUtils.getLoginUser().getUserId());
        return tempCxMapper.selectTempCxList(tempCx);
    }

    @Override
    public List<TempCx> selectTempCxXsList(TempCx tempCx) {
        tempCx.setCreateId(SecurityUtils.getLoginUser().getUserId());
        return tempCxMapper.selectTempCxXsList(tempCx);
    }

    /**
     * 新增采销
     * 
     * @param tempCx 采销
     * @return 结果
     */
    @Override
    public int insertTempCx(TempCx tempCx)
    {
        tempCx.setCreateId( SecurityUtils.getLoginUser().getUserId());
        return tempCxMapper.insertTempCx(tempCx);
    }

    /**
     * 修改采销
     * 
     * @param tempCx 采销
     * @return 结果
     */
    @Override
    public int updateTempCx(TempCx tempCx)
    {
        return tempCxMapper.updateTempCx(tempCx);
    }

    @Override
    public int deleteTempCxByTIds(Long[] tIds) {
        return 0;
    }

//    /**
//     * 批量删除采销
//     *
//     * @param tIds 需要删除的采销主键
//     * @return 结果
//     */
//    @Override
//    public int deleteTempCxByTIds(Long[] tIds)
//    {
//        return tempCxMapper.deleteTempCxByTIds(tIds);
//    }

    /**
     * 删除采销信息
     * 
     * @param tId 采销主键
     * @return 结果
     */
    @Override
    public int deleteTempCxByTId(Long tId)
    {
        return tempCxMapper.deleteTempCxByTId(tId);
    }

    @Override
    public AjaxResult insertProductsId(List<Long> ids) {
        for (Long id : ids) {
            TempCx tempCx = new TempCx();
            tempCx.setProductId(id);
            tempCx.setCreateId(SecurityUtils.getLoginUser().getUserId());
            tempCxMapper.insertTempCx(tempCx);
        }
        return AjaxResult.success();
    }
    @Transactional
    @Override
    public AjaxResult insertDd(TempCxDdVO tempCxDdVO) {
        String qz = "";
        if(tempCxDdVO.getIsType() == 1){
            qz = "CG";
        }else if(tempCxDdVO.getIsType() == 2){
            qz = "CT";
        }else if(tempCxDdVO.getIsType() == 3){
            qz = "XS";
        }else if(tempCxDdVO.getIsType() == 4){
            qz = "XT";
        }
        // 获取当前时间戳，用于生成订单
        long timestamp = System.currentTimeMillis();
        String code = ""; //单号
        TempCx tempCx = new TempCx();
        tempCx.setCreateId(SecurityUtils.getLoginUser().getUserId());
        TempCx t = tempCxMapper.selectSumCountAndSumPrice(tempCx);

        if(tempCxDdVO.getIsType() == 1 || tempCxDdVO.getIsType() ==2 ){
            //采购
            Purchase purchase = new Purchase();
            purchase.setSupplyId(tempCxDdVO.getSupplyId());
            if(tempCxDdVO.getIsType() == 1){
                purchase.setZnum(t.getZsum());
                purchase.setZprice(t.getZprice());
            }else{
                purchase.setZnum(t.getZsum()== 0? t.getZsum(): t.getZsum()* -1);
                purchase.setZprice(t.getZprice().compareTo(BigDecimal.ZERO) == 0 ? t.getZprice() : t.getZprice().multiply(new BigDecimal("-1")));
            }
            purchase.setCreateName(sysUserMapper.selectUserById(t.getCreateId()).getUserName());
            purchase.setCreateTime(LocalDateTime.now());
            purchase.setIsSh("1");
            purchase.setIsCt(tempCxDdVO.getIsType().toString());
            purchase.setIsZf("0");
            purchase.setIsZd("0");
            purchase.setIsRk(tempCxDdVO.getIsType()== 1 ?  "0" : "2");
            purchaseMapper.insertPurchase(purchase);
            Long purchaseId = purchase.getPurchaseId();
            code = qz + timestamp + purchaseId;
            purchase.setPurchaseCode(code);
            purchaseMapper.updatePurchase(purchase);
            //插入详情表
            List<TempCx> list = tempCxMapper.selectTempCxList(tempCx);
            for (TempCx cx : list) {
                Xqpurchase x = new Xqpurchase();
                x.setPurchaseId(purchaseId);
                x.setProductId(cx.getProductId());
                if(tempCxDdVO.getIsType() == 1){
                    x.setSum(cx.getTSum());
                    x.setZprice(cx.getTZPrice());
                }else{
                    x.setSum(cx.getTSum() == 0 ? cx.getTSum() : cx.getTSum() * -1);
                    x.setZprice(cx.getTZPrice().compareTo(BigDecimal.ZERO) == 0 ? cx.getTZPrice() : cx.getTZPrice().multiply(new BigDecimal("-1")));
                }
                x.setPrice(cx.getTPrice());
                x.setIsRk("0");
                x.setBatch(cx.getBatch());
                xqpurchaseMapper.insertXqpurchase(x);
            }
        }
        if(tempCxDdVO.getIsType() == 3 || tempCxDdVO.getIsType() == 4){
            //销售
            Sale sale = new Sale();
            sale.setSupplyId(tempCxDdVO.getSupplyId());
            if(tempCxDdVO.getIsType() == 3){
                sale.setZnum(t.getZsum());
                sale.setZprice(t.getZprice());
            }else{
                sale.setZnum(t.getZsum()== 0? t.getZsum(): t.getZsum()* -1);
                sale.setZprice(t.getZprice().compareTo(BigDecimal.ZERO) == 0 ? t.getZprice() : t.getZprice().multiply(new BigDecimal("-1")));
            }
            sale.setCreateName(sysUserMapper.selectUserById(t.getCreateId()).getUserName());
            sale.setCreateTime(LocalDateTime.now());
            sale.setIsXt(tempCxDdVO.getIsType().toString());
            sale.setIsZf("0");
            sale.setIsRk(tempCxDdVO.getIsType() == 3 ? "2" : "0");
            sale.setIsSh("1");
            sale.setIsZd("0");
            saleMapper.insertSale(sale);
            Long saleId = sale.getSaleId();
            code = qz + timestamp + saleId;
            sale.setSaleCode(code);
            saleMapper.updateSale(sale);
            //插入详情表
            List<TempCx> list = tempCxMapper.selectTempCxList(tempCx);
            for (TempCx cx : list) {
                Xqsale x = new Xqsale();
                x.setSaleId(saleId);
                x.setProductId(cx.getProductId());
                if(tempCxDdVO.getIsType() == 3){
                    x.setSum(cx.getTSum());
                    x.setZprice(cx.getTZPrice());
                }else{
                    x.setSum(cx.getTSum() == 0 ? cx.getTSum() : cx.getTSum() * -1);
                    x.setZprice(cx.getTZPrice().compareTo(BigDecimal.ZERO) == 0 ? cx.getTZPrice() : cx.getTZPrice().multiply(new BigDecimal("-1")));
                }
                x.setPrice(cx.getTPrice());
                Stock stock = stockMapper.selectStockBatch(cx.getBatch());
                if(tempCxDdVO.getIsType() == 3){
                    x.setProfit((cx.getTPrice().subtract(stock.getCjPrice())).multiply(BigDecimal.valueOf(cx.getTSum())));
                }else{
                    x.setProfit(((cx.getTPrice().subtract(stock.getCjPrice())).multiply(BigDecimal.valueOf(cx.getTSum()))).multiply(new BigDecimal("-1")));
                }

                x.setBatch(cx.getBatch());
                xqsaleMapper.insertXqsale(x);
            }
        }
        tempCxMapper.deleteTempCx(SecurityUtils.getLoginUser().getUserId());
        return AjaxResult.success(code);
    }

    @Override
    public AjaxResult selectTempDdCc(TempCxCcVO tempCxCcVO) {
        TempCx t = new TempCx();
        t.setCreateId(SecurityUtils.getLoginUser().getUserId());
        t.setProductId(tempCxCcVO.getProductId());
        t.setBatch(tempCxCcVO.getBatch());
        Long sum = tempCxMapper.selectTempCxSum(t);
        Long kcSum = tempCxMapper.selectKcSum(t);
        if(kcSum > 0){
            return AjaxResult.error(98,"已经添加这一批次商品！，请误重复添加！");
        }else{
            if(sum > 1){
                return AjaxResult.error(99,"同商品最多2条记录！");
            }else{
                TempCx tempCx  = tempCxMapper.selectTempCx(t);
                if(tempCx != null){
                    return AjaxResult.error(100,"该商品已经添加了！");
                }else{
                    Product product = productMapper.selectProductByProductId(tempCxCcVO.getProductId());
                    if(product.getStatus().equals("1")){
                        return  AjaxResult.error(101,"该商品已停用！");
                    }else{
                        return AjaxResult.success();
                    }
                }
            }
        }


    }

    @Override
    public AjaxResult deleteAll() {
        tempCxMapper.deleteTempCx(SecurityUtils.getLoginUser().getUserId());
        return AjaxResult.success();
    }


}
